﻿using System.Collections.ObjectModel;
using System.Windows;
using DesktopToyWpf.Services;
using DesktopToyWpf.ViewModels;

namespace DesktopToyWpf;

public static class Global
{
    public const string AppName = "DesktopToyWpf";
    
    public static MainService MainService;
    public static MainViewModel MainViewModel;
    public static Storage Storage;
    public static DayStorage CurrentDayStorage;
    public static Config Config;
    public static MainWindow MainWindow;


    public static void OnStartup()
    {
        // 读配置
        Config = Config.ReadConfig();
        Storage = Storage.Load();
        
        // 初始化服务
        MainService = new MainService();
        MainService.Start();
        
        // 初始化界面逻辑
        InitViewModel();
        
        // 显示主界面
        MainWindow = new MainWindow();
        MainWindow.Show();
    }

    public static void OnClosed()
    {
        SaveStorage();
        MainService.Stop();
    }

    public static void SaveStorage()
    {
        CurrentDayStorage.MoodPoints = MainViewModel.MoodPoints.ToList();
        CurrentDayStorage.HappyCount = MainViewModel.HappyCount;
        Storage.Save();
    }
    
    public static void InitViewModel()
    {
        var now = DateTime.Now;
        
        // 有存储就先读存储
        var dayStorage = Storage.Days.FirstOrDefault(x => x.Year == now.Year && x.Month == now.Month && x.Day == now.Day);
        if (dayStorage == null)
        {
            dayStorage = new DayStorage
            {
                Year = now.Year,
                Month = now.Month,
                Day = now.Day
            };
            
            Storage.Days.Add(dayStorage);
        }

        CurrentDayStorage = dayStorage;
        MainViewModel = new MainViewModel
        {
            Now = now,
            MoodPoints = new ObservableCollection<Point>(dayStorage.MoodPoints),
            HappyCount = dayStorage.HappyCount
        };
    }
}